const os = require("os");
const fs = require("fs");
const { readdir, stat } = require("fs/promises");
const { resolve, join } = require("path");
const OSS = require("ali-oss");
const ossPath = "uniapp-vue3";

//获取本机环境变量(配置在～/.zshrc中)
const env = process.env;
const { OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, OSS_REGION, OSS_BUCKET } =
  env;

const client = new OSS({
  region: OSS_REGION,
  accessKeyId: OSS_ACCESS_KEY_ID,
  accessKeySecret: OSS_ACCESS_KEY_SECRET,
  bucket: OSS_BUCKET,
});

const basePath = resolve(process.cwd(), "src/assets/images");
const uploadPath = ossPath;
async function getPath(p, uP) {
  const res = await readdir(p);
  let ind = 0;
  while (ind < res.length) {
    const curPath = resolve(p, res[ind]);
    const r = await stat(curPath);
    const ossUploadPath = join(uP, res[ind]);
    if (r.isDirectory()) {
      if (!/local/.test(ossUploadPath)) {
        await getPath(curPath, ossUploadPath);
      }
    } else {
      await putStream(curPath, ossUploadPath);
    }
    ind++;
  }
}

async function putStream(curPath, ossUploadPath) {
  try {
    // use 'chunked encoding'
    // let stream = fs.createReadStream('local-file');
    // let result = await client.putStream('object-name', stream);
    // console.log(result);

    // don't use 'chunked encoding'
    const stream = fs.createReadStream(curPath);
    const size = fs.statSync(curPath).size;
    await client.putStream(ossUploadPath, stream, { contentLength: size });
    console.log(`\u001b[32;1m ${ossUploadPath}  上传成功 ${os.EOL} `);
  } catch (e) {
    console.log(e);
  }
}

getPath(basePath, uploadPath).then(() => {
  // console.log(resultArr);
});
